<template>
    <div class="app-container">
        <div class="table-wrapper">
            <h4>重大工程历史震害数据</h4>
            <el-form class="form-inline" :inline="true" ref="queryRef" :rules="rules" label-position="right" :model="params"
                label-width="200px">
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="编号：" class="form-item" prop="code">
                            <el-input v-model="params.code" placeholder="" :disabled="true" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="地震名称：" class="form-item" prop="seismName">
                            <el-input v-model="params.seismName" placeholder="" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="设防情况：" class="form-item" prop="fortification">
                            <el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable disabled>
                                <el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="年代：" class="form-item" prop="year">
                            <el-select v-model="params.year" placeholder="请选择" class="form-select" clearable>
                                <el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="震级：" class="form-item" prop="magnitude">
                            <el-input v-model="params.magnitude" placeholder="" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="重大工程类别：" class="form-item" prop="projectType">
                            <el-select v-model="params.projectType" placeholder="" class="form-select" clearable>
                                <el-option v-for="item in heavyCategoryOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="发生时间:" class="form-item" prop="createTime">
                            <el-date-picker v-model="params.createTime" type="datetime" placeholder="选择日期时间" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY-MM-DD" time-format="HH:mm:ss" />
                            <!-- <el-date-picker v-model="params.createTime" type="date"
                                placeholder="选择日期">
                            </el-date-picker> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="11"></el-col>
                </el-row>
                <el-row justify="end">
                    <el-form-item class="bottom-button">
                        <el-button type="primary" @click="handleSave()" v-if="route.query.isEdit">保存</el-button>
                        <!-- <el-button type="primary" @click="importParmsClick('historyEarthquakeDamage')">导入</el-button> -->
                    </el-form-item>
                </el-row>
            </el-form>
            <el-form :inline="true" ref="tableRef" :rules="rules" label-position="right" :model="tableFormData">
                <el-table class="listTables" ref="multipleTableRef" border :data="tableFormData.tableData"
                    style="width: 100%" @selection-change="handleSelectionChange"
                    :cell-style="{ border: '1px solid #e5ebf7' }"
                    :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
                    <el-table-column type="index" width="55" label="序号" />
                    <el-table-column header-align="center" align="center" label="地震动参数（烈度）">
                        <template #default="scope">
                            <el-form-item :prop="`tableData.${scope.$index}.params`" :rules="rules.params">
                                <el-select v-model="scope.row.params" size="small" disabled>
                                    <el-option v-for="item in paramsOptions" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column header-align="center" align="center" label="破坏状态">
                        <template #default="scope">
                            <el-form-item :prop="`tableData.${scope.$index}.breakState`" :rules="rules.breakState">
                                <el-select v-model="scope.row.breakState" size="small" :disabled="scope.row.isEdit">
                                    <el-option v-for="item in breakStateOptions" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <el-dialog v-model="dialogVisible" title="导入数据" width="30%">
                <div class="downloadModel">
                    下载导入模板<span @click="importTemplate">{{ downloadFileName }}</span>
                </div>
                <el-upload ref="uploadRef" :action="uploadFileUrl" :before-upload="beforeUpload"
                    :before-remove="beforeRemove" :on-success="uploadSuccess" :on-error="uploadError"
                    :file-list.sync="fileList" :headers="headers" :multiple="false" :limit="1" :auto-upload="false">
                    <el-button type="primary" class="icon-Angle-upload">
                        选择本地文件
                    </el-button>
                </el-upload>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button size="medium" @click="cancleUpload">取 消</el-button>
                        <el-button size="medium" type="primary" @click="submitUpload">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { reactive, toRefs } from "vue";
import { getToken } from "@/utils/auth";
// 引入接口
import {
    updateHeDamage,
    getHeDamageByNumber,
    update,
    importHeDamageData
} from "@/api/majorEnginVulnerAnalysis/majorEnginVulnerAnalysis.js";
// 引入store
import useDictStore from '@/store/modules/dict';
// 获取pinia
const dictStore = useDictStore();

// 获取当前实例
const { proxy } = getCurrentInstance();
// 当前路由对象
const route = useRoute();

// 接口根路径
const baseURL = import.meta.env.VITE_APP_BASE_API;
// 设置token
const headers = ref({ token: "token " + getToken() });

// 数据导入
const uploadRef = ref()
const dialogVisible = ref(false)
// 取消上传
const cancleUpload = (res) => {
    dialogVisible.value = false
}
// 提交上传
const submitUpload = (res) => {
    uploadRef.value.submit()
}
// 上传地址
const uploadFileUrl = ref(baseURL + "/importData/importHeDamageData");
// 文件列表
const fileList = ref([]);
// 模板名称
const downloadFileName = ref('历史震害数据模板.xlsx');
const importParmsClick = (val) => {
    fileList.value = [];
    switch (val) {
        case 'historyEarthquakeDamage':
            dialogVisible.value = true
            downloadFileName.value = '历史震害数据模板.xlsx'
            uploadFileUrl.value = baseURL + "/importData/importHeDamageData"
            break;
        default:
            break;
    }
}
// 模板下载
function importTemplate() {
    proxy.download("/base/product/downloadExcel", {
        fileName: downloadFileName.value
    }, downloadFileName.value);
};
//文件上传
const beforeRemove = () => {
    fileList.value = [];
};
// 上传前回调
const beforeUpload = (file) => {
    const fileSize = file.size / 1024 / 1024;
    if (fileSize > 200) {
        $message.error('文件大小不能超过200M!');
        return false;
    }
    const fileReg = /.xls|.xlsx/;
    if (!fileReg.test(file.name)) {
        $message.error('请选择.xls .xlsx格式文件');
        return false;
    }
    return true;
};
// 上传完成回调
const uploadSuccess = (response, uploadFile, uploadFiles) => {
    if (response.code === 200) {
        proxy.$modal.msgSuccess("上传文件成功");
        dialogVisible.value = false
        //onSearch()
    } else {
        proxy.$modal.msgError(response.message || "导入失败，请检查表头是否改动");
    }
}
// 上传失败回调
const uploadError = (response, uploadFile, uploadFiles) => {
    proxy.$modal.msgError(response.message || "导入失败，请检查表头是否改动");
}

//最多保留N小数 ,N 在 options {decimals: N} 中定义
const positivedecimals = (rule, value, callback) => {
    value = String(value);
    if (
        value.indexOf(".") != -1 &&
        (value.split(".").length > rule.options.decimals ||
            value.split(".")[0] === "" ||
            value.split(".")[1] === "")
    ) {
        callback(new Error()); //防止输入多个小数点
    } else if (
        value.indexOf(".") != -1 &&
        value.split(".")[1].length > rule.options.decimals
    ) {
        callback(new Error()); //小数点后两位
    } else {
        callback();
    }
};

const data = reactive({
    // 表单参数
    params: {
        code: "",//编号
        magnitude: "",//震级
        year: "",//年代
        fortification: "", //设防情况
        userName: "", //维护人
        projectType: "",//震级
        createTime: "",//发生时间
    },
    rules: {
        code: [
            { required: true, message: '', trigger: 'blur' },
        ],
        seismName: [
            { required: false, message: "请输入地震名称", trigger: "blur" },
            { max: 100, message: "最多输入100个字", trigger: ["change", "blur"] },
        ],
        fortification: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        year: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        projectType: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        createTime: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        magnitude: [
            { required: true, message: "请输入震级", trigger: "blur" },
            { max: 20, message: "最多输入20个字", trigger: ["change", "blur"] },
        ],
        params: [
            { required: true, message: "请输入", trigger: "blur" },
            {
                message: "请输入正确数值，最多保留四位小数",
                validator: positivedecimals,
                options: { decimals: 4 },
                trigger: ["change", "blur"],
            }
        ],
        breakState: [
            { required: true, message: "请输入", trigger: "blur" },
            { max: 100, message: "最多输入100个字", trigger: ["change", "blur"] },
        ],
    },
    // 设防情况
    fortificationOptions: dictStore.fortificationOptions || [],
    // 年份
    yearsOptions: dictStore.yearsOptions1 || [],
    // 重大工程类别
    heavyCategoryOptions: dictStore.heavyCategoryOptions || [],
    //表格
    tableFormData: {
        tableData: [
            {
                params: '',
                breakState: '',
            }
        ],
    },
    paramsOptions:[{value:6,label:'6'},{value:7,label:'7'},{value:8,label:'8'},{value:9,label:'9'},{value:10,label:'10'},{value:11,label:'11'},{value:12,label:'12'}],
    breakStateOptions:[{value:'基本完好',label:'基本完好'},{value:'轻微破坏',label:'轻微破坏'},{value:'中等破坏',label:'中等破坏'},{value:'严重破坏',label:'严重破坏'},{value:'倒塌',label:'倒塌'},{value:'-',label:'-'}],
})
const {
    params,
    fortificationOptions,
    yearsOptions,
    heavyCategoryOptions,
    tableFormData,
    rules,
    paramsOptions,
    breakStateOptions
} = toRefs(data);


//表格
// 表格多选列表
const multipleTableRef = ref();
// 表格选择事件
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};
//新增行
const handleCalcAdd = () => {
    tableFormData.value.tableData.push({
        params: "",
        breakState: ""
    })
}

//修改 保存
const handleBrickModify = (index, row) => {
    if (row.isEdit) {
        let query = [
            {
                "ciphdId": row.ciphdId, //id
                "seismName": row.seismName, //地震名称
                "seismTime": row.seismTime, //发生时间
                "magnitude": row.magnitude, //震级
                "projectType": params.value.projectType, //重大工程类别
                "fortification": params.value.fortification, //设防情况
                "years": params.value.years, //年代
                "params": row.params, //地震动参数
                "breakState": row.breakState, //破坏状态
            }
        ]
        updateHeDamage(query).then((res) => {
            if (res.code === 200) {
                proxy.$modal.msgSuccess('修改成功!');
                row.isEdit = false
            } else {
                proxy.$modal.msgError('修改失败!');
            }
        }).catch(err => {
            console.log(err);
        });
    } else {
        row.isEdit = true
    }
}

function getDateTime(chinaStandard) {
      var date = new Date(chinaStandard);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
      h = h < 10 ? ('0' + h): h;
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      let s = date.getSeconds();
      s = s < 10 ? ('0' + s): s;
      return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + s;  //这里如果不需要小时 分  后边的可以不需要拼接
}

// 保存
const handleSave = () =>{
    proxy.$refs['queryRef'].validate((valid, fields)=>{
    if(valid){
        let table = proxy.$refs['tableRef'].validate(async (valid, fields) => { valid, fields });
        if(!table) return;
        let obj = {};
        tableFormData.value.tableData.forEach(item=>{
            obj[item.params] = item.breakState;
        })
        const createTime = getDateTime(params.value.createTime);
        let query = {...params.value,seismDate:createTime.split(' ')[0],seismTime:createTime.split(' ')[1],map:obj,id:route.query.id};
        update(query).then(res=>{
            if (res.code === 200) {
                proxy.$modal.msgSuccess('修改成功!');
            }
        }).catch(err=>{console.log(err);})
      }
    })
}

// 挂载
onMounted(() => {
    const id = route.query.id;
    getHeDamageByNumber(id).then((res) => {
        const rows = res.data;
        tableFormData.value.tableData = []
        if (res.code === 200) {
            //循环遍历之前加上非空判断
            for (const key in res.data.map) {
                tableFormData.value.tableData.push({breakState:res.data.map[key],params:key,isEdit:!route.query.isEdit})
            }
            // 绑定表格第一行数据
            params.value = res.data.majorProjectsVo;
            params.value.createTime = `${res.data.majorProjectsVo.seismDate} ${res.data.majorProjectsVo.seismTime}`
        }
    }).catch(err => {
        console.log(err);
    });
});
</script>

<style lang="scss">
.table-wrapper {
    position: relative;

    h4 {
        font-size: 16px;
        font-weight: bold;
        color: #107ce5;
        text-align: center;
    }
}

.form-inline {
    .el-form-item {
        margin-right: 0;
    }
}

.downloadModel {
    font-size: 16px;
    line-height: 60px;

    span {
        color: #107ce5;
        cursor: pointer;
    }
}
</style>


